package com.clh.controller;
/*
 * 邱宏宇
 */
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.clh.common.PageInfo;
import com.clh.dto.Result;
import com.clh.entity.Family;
import com.clh.service.FamilyService;
import com.clh.service.impl.FamilyServiceImpl;
import com.clh.util.RegexUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Servlet implementation class FamilyServlet
 */
@WebServlet("/FamilyServlet")
@MultipartConfig
public class FamilyServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private FamilyService familyService = new FamilyServiceImpl();

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String op = request.getParameter("op");
		if ("page".equals(op)) {//分页查询
			doQueryByPage(request, response);
		}else if("add".equals(op)) {//添加
			doAdd(request,response);
		}else if("delete".equals(op)) {//删除
			doDel(request,response);
		}else if("modify".equals(op)) {//修改
			doModify(request,response);
		}else if("getByCard".equals(op)) {//依据身份证返回family对象
			doGetByCard(request,response);
		}else if("list".equals(op)) {//前台登录后返回同房号family对象列表
			doGetList(request,response);
		}
	}

	/* @Description:（方法功能描述）
	* @param request
	* @param response（展示方法参数和返回值）
	*/
	private void doGetList(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 返回统一的结果对象
		Result result = new Result();
		
		//获取前端参数
		String roomNo = request.getParameter("roomNo");
		
		if(roomNo!=null && !"".equals(roomNo)) {
			//调用业务
			List<Family> list = familyService.getListByRoomNo(roomNo);
			if(list!=null) {
				result.ok(list);
				
			}else {
				result.fail(0, "查无数据！");
			}
		}else {
			result.fail(0, "未获取参数，获取家庭成员列表失败");
		}
		
		//响应
		response.setContentType("application/json;charset=utf-8");
		ObjectMapper objectMapper = new ObjectMapper();
		String json = objectMapper.writeValueAsString(result);
		response.getWriter().write(json);
	}

	/* @Description:（方法功能描述）
	* @param request
	* @param response（展示方法参数和返回值）
	*/
	private void doGetByCard(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 返回统一的结果对象
		Result result = new Result();
		
		String familyCard = request.getParameter("familyCard");
		
		Family family = new Family();
		if(familyCard!=null) {
			//调用业务
			family = familyService.getFamilyByFamilyCard(familyCard);
		}
		
		if(family == null) {
			result.fail(0, "未获取对象");
		}else {
			result.ok(family);
		}
		
		//响应
		response.setContentType("application/json;charset=utf-8");
		ObjectMapper objectMapper = new ObjectMapper();
		String json = objectMapper.writeValueAsString(result);
		response.getWriter().write(json);
	}

	/* @Description:（方法功能描述）
	* @param request
	* @param response（展示方法参数和返回值）
	*/
	private void doModify(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		// 返回统一的结果对象
		Result result = new Result();
		
		//获取前端参数
		String familyName = request.getParameter("familyName");
		String familyCard = request.getParameter("familyCard");
		String roomNo = request.getParameter("roomNo");
		String familyTypeId = request.getParameter("familyTypeId");
		String familyPhone = request.getParameter("familyPhone");
		//获取图片文件
		Part part = request.getPart("familyImage");
		
		
		//校验身份证号码和手机号码
		if(familyCard!=null && RegexUtil.validateOwnerId(familyCard)
						&& familyPhone!=null && RegexUtil.validatePhoneNumber(familyPhone)) {
			//构建family对象
			Family family = new Family();
			family.setFamilyName(familyName);
			family.setFamilyCard(familyCard);
			family.setRoomNo(roomNo);
			family.setFamilyTypeId(Integer.valueOf(familyTypeId));
			family.setFamilyPhone(familyPhone);
			
			boolean errorFlag = false;
			if (part.getSize() > 0) {// 判断是否包含文件，此分支为包含
				// 获取文件内容类型
				String contentType = part.getContentType();
				// 支持的文件内容类型
				String allowedContentType = "image/jpeg;image/png;image/gif";
				// 校验文件类型是否合法
				if (allowedContentType.indexOf(contentType) == -1) {
					// 设置响应对象
					result.fail(0, "文件：" + part.getSubmittedFileName() + "文件类型不合法");
					errorFlag = true;
				} else if (part.getSize() > 102400) {// 校验文件大小是否合法
					result.fail(0, "文件：" + part.getSubmittedFileName() + "文件大小不合法");
					errorFlag = true;
				} else {
					// 获取源文件名
					String fileName = part.getSubmittedFileName();

					// 用精简的UUID保证存储的文件名唯一
					UUID uuid = UUID.randomUUID();
					StringBuffer storeFileName = new StringBuffer();

					// 不保留源文件名，唯一序列加后缀
					storeFileName.append(uuid).append(fileName.substring(fileName.lastIndexOf(".")));

					// 存储文件
					// File类关联存储文件的目录
					File file = new File("E:\\upload\\image");

					// 定义文件完整路径
					StringBuilder filePath = new StringBuilder();
					filePath.append(file).append(File.separator).append(storeFileName);

					// 将上传的文件写到指定的服务器
					part.write(filePath.toString());

					// 设置响应对象
					//result.ok(true).setMessage("提交成功，并存储文件");

					// 对商品对象的图片属性赋值
					family.setFamilyImage(storeFileName.toString());
					
					
				}

			}
			if (!errorFlag) {//图片校验和存储成功
				// 调用业务层
				boolean f = familyService.modifyFamily(family);
				if (f) {
					result.ok("修改家庭成员成功！");
				} else {
					result.fail(0, "修改家庭成员失败！");
				}
			}
		}else {
			result.fail(0, "修改失败！身份证或手机号不合法");
		}
		
		//响应
		response.setContentType("application/json;charset=utf-8");
		ObjectMapper objectMapper = new ObjectMapper();
		String json = objectMapper.writeValueAsString(result);
		response.getWriter().write(json);
		
		
	}

	/* @Description:（方法功能描述）
	* @param request
	* @param response（展示方法参数和返回值）
	*/
	private void doDel(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 返回统一的结果对象
		Result result = new Result();
		
		//获取参数（身份证号码）
		String familyCard = request.getParameter("familyCard");
		
		if(familyCard==null && "".equals(familyCard)) {
			result.fail(0, "所传参数为空 删除失败");
		}else {
			//调用业务
			boolean flag = familyService.delFamily(familyCard);
			if(flag) {
				result.ok(true).setMessage("删除成功");
			}else {
				result.fail(0, "删除失败");
			}
		}
		
		//响应
		response.setContentType("application/json;charset=utf-8");
		ObjectMapper objectMapper = new ObjectMapper();
		String json = objectMapper.writeValueAsString(result);
		response.getWriter().write(json);
	}

	/* @Description:（添加家庭成员）
	* @param request
	* @param response（展示方法参数和返回值）
	*/
	private void doAdd(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		// 返回统一的结果对象
		Result result = new Result();
		//获取前端参数并构建家庭成员对象
		String familyName = request.getParameter("familyName");
		String familyCard = request.getParameter("familyCard");
		String roomNo = request.getParameter("roomNo");
		String familyTypeId = request.getParameter("familyTypeId");
		String familyPhone = request.getParameter("familyPhone");
		//获取图片文件
		Part part = request.getPart("familyImage");
		
		//校验身份证号码和手机号码
		if(familyCard!=null && RegexUtil.validateOwnerId(familyCard)
				&& familyPhone!=null && RegexUtil.validatePhoneNumber(familyPhone)) {
			//构建family对象
			Family family = new Family();
			family.setFamilyName(familyName);
			family.setFamilyCard(familyCard);
			family.setRoomNo(roomNo);
			family.setFamilyTypeId(Integer.valueOf(familyTypeId));
			family.setFamilyPhone(familyPhone);
			
			boolean errorFlag = false;
			if (part.getSize() > 0) {// 判断是否包含文件
				// 获取文件内容类型
				String contentType = part.getContentType();
				// 支持的文件内容类型
				String allowedContentType = "image/jpeg;image/png;image/gif";
				// 校验文件类型是否合法
				if (allowedContentType.indexOf(contentType) == -1) {
					// 设置响应对象
					result.fail(0, "文件：" + part.getSubmittedFileName() + "文件类型不合法");
					errorFlag = true;
				} else if (part.getSize() > 102400) {// 校验文件大小是否合法
					result.fail(0, "文件：" + part.getSubmittedFileName() + "文件大小不合法");
					errorFlag = true;
				} else {
					// 获取源文件名
					String fileName = part.getSubmittedFileName();

					// 用精简的UUID保证存储的文件名唯一
					UUID uuid = UUID.randomUUID();
					StringBuffer storeFileName = new StringBuffer();

					// 不保留源文件名，唯一序列加后缀
					storeFileName.append(uuid).append(fileName.substring(fileName.lastIndexOf(".")));

					// 存储文件
					// File类关联存储文件的目录
					File file = new File("E:\\upload\\image");

					// 定义文件完整路径
					StringBuilder filePath = new StringBuilder();
					filePath.append(file).append(File.separator).append(storeFileName);

					// 将上传的文件写到指定的服务器
					part.write(filePath.toString());

					// 设置响应对象
					//result.ok(true).setMessage("提交成功，并存储文件");

					// 对商品对象的图片属性赋值
					family.setFamilyImage(storeFileName.toString());
				}

			}
			
			System.out.println(family.getFamilyImage());
			
			
			if (!errorFlag) {//图片校验和存储成功
				// 调用业务层
				boolean f = familyService.addFamily(family);
				if (f) {
					result.ok("添加家庭成员成功！");
				} else {
					result.fail(0, "添加家庭成员失败！");
				}
			}
		}else {
			result.fail(0, "添加失败！身份证号码或手机号不合法");
		}
		
		//响应
		response.setContentType("application/json;charset=utf-8");
		ObjectMapper objectMapper = new ObjectMapper();
		String json = objectMapper.writeValueAsString(result);
		response.getWriter().write(json);
	}

	/*
	 * @Description:（方法功能描述）
	 * 
	 * @param request
	 * 
	 * @param response（展示方法参数和返回值）
	 */
	private void doQueryByPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 返回统一的结果对象
		Result result = new Result();

		// 获取前端所传参数
		String pageNum = request.getParameter("pageNum");
		String pageSize = request.getParameter("pageSize");
		String familyName = request.getParameter("familyName");
		String familyCard = request.getParameter("familyCard");
		String roomNo = request.getParameter("roomNo");

		// 校验参数
		if (pageNum == null || "".equals(pageNum) || Integer.parseInt(pageNum) < 0 || pageSize == null
				|| "".equals(pageSize) || Integer.parseInt(pageSize) < 0) {
			result.fail(0, "参数错误");
		} else {
			// 调用业务层
			Family family = new Family();
			family.setFamilyName(familyName);
			family.setFamilyCard(familyCard);
			family.setRoomNo(roomNo);

			PageInfo pageInfo = familyService.getFamilyByPage(family, Integer.parseInt(pageNum),
					Integer.parseInt(pageSize));

			if (!pageInfo.getList().isEmpty()) {
				result.ok(pageInfo);
			} else {
				result.fail(0, "没有相关数据");
			}
		}

		// 设置响应
		response.setContentType("application/json;charset=utf-8");
		ObjectMapper objectMapper = new ObjectMapper();
		String json = objectMapper.writeValueAsString(result);

		response.getWriter().write(json);
		
	}

}
